/*
 * @Author: lsjweiyi
 * @Date: 2023-07-23 15:30:59
 * @LastEditors: lsjweiyi
 * @LastEditTime: 2023-07-29 22:19:52
 * @Description:该中间件限制整个服务的访问量，利用标准库，性能好，是令牌桶原理
 * Copyright (c) 2023 by lsjweiyi, All Rights Reserved.
 */
package middleware

import (
	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
)

/**
 * @description: 该中间件限制整个服务的访问量，利用标准库，性能好，是令牌桶原理
 * @return {*}
 */
func LimitHandler() gin.HandlerFunc {
	lmt := rate.Limit(20)
	lmter := rate.NewLimiter(lmt, 10)

	return func(c *gin.Context) {
		if !lmter.Allow() {
			c.Data(429, "text/html", nil)
			c.Abort()
		} else {
			c.Next()
		}
	}
}
